package com.xiaoq.positionmarket.repository.impl;

import com.xiaoq.positionmarket.entity.UserTrackEntity;
import com.xiaoq.positionmarket.repository.IUserTrackRepository;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by chenjh on 2018/4/8.
 */
@Repository
public class UserTrackRepositoryImpl implements IUserTrackRepository {

    @Autowired
    private Datastore datastore;

    @Override
    public boolean save(UserTrackEntity userTrackEntity) {
        if(userTrackEntity == null || StringUtils.isBlank(userTrackEntity.getId())){
            return false;
        }
        datastore.save(userTrackEntity);
        return true;
    }

    @Override
    public List<UserTrackEntity> getUserTrackList(double longitude, double latitude, long maxDistance, Long startTime, Long endTime) {
        double distance = maxDistance / (1000.0 * 111);

        Query<UserTrackEntity> query = datastore.createQuery(UserTrackEntity.class).field("loc")
                .near(longitude, latitude, distance);
        if(startTime != null){
            query.filter("createdAt >= ", startTime);
        }
        if(endTime != null){
            query.filter("createdAt <= ", endTime);
        }

        return query.asList();
    }
}
